using B.S.XZYData.Api.Wrter.Application.Command.WorkOrder;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Wrter.Application.Handler.WorkOrder
{
    /// <summary>
    /// 结束工单处理器
    /// </summary>
    public class FinishWorkOrderHandler : IRequestHandler<FinishWorkOrderCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<WorkOrderModel> _workOrderRepo;
        private readonly ILogger<FinishWorkOrderHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="workOrderRepo">工单仓储</param>
        /// <param name="logger">日志记录器</param>
        public FinishWorkOrderHandler(
            IBaseRepository<WorkOrderModel> workOrderRepo,
            ILogger<FinishWorkOrderHandler> logger)
        {
            _workOrderRepo = workOrderRepo;
            _logger = logger;
        }

        /// <summary>
        /// 结束工单
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回统一包装类</returns>
        public async Task<ApiResult<bool>> Handle(FinishWorkOrderCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<bool>();

            try
            {
                // 设置默认操作人
                if (string.IsNullOrWhiteSpace(request.OperateBy))
                {
                    request.OperateBy = "System";
                }

                // 检查工单是否存在
                var workOrder = await _workOrderRepo.GetValue(request.Id);
                if (workOrder == null)
                {
                    res.Code = ApiEnum.Error;
                    res.Msg = "工单不存在";
                    return res;
                }

                // 检查工单状态
                if (workOrder.Status == "已结束")
                {
                    res.Code = ApiEnum.Error;
                    res.Msg = "工单已经结束，无需重复结束";
                    return res;
                }

                if (workOrder.Status == "未开始")
                {
                    res.Code = ApiEnum.Error;
                    res.Msg = "工单未开始，无法直接结束";
                    return res;
                }

                // 更新工单状态和实际结束时间
                workOrder.Status = "已结束";
                workOrder.ActualEndTime = DateTime.Now;
                workOrder.UpdateBy = request.OperateBy;
                workOrder.UpdateTime = DateTime.Now;

                await _workOrderRepo.UpdateAsync(workOrder);

                _logger.LogInformation($"结束工单成功：{workOrder.Code}，操作人：{request.OperateBy}");

                res.Data = true;
                res.Code = ApiEnum.Success;
                res.Msg = "结束工单成功";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"结束工单失败，工单ID：{request.Id}，操作人：{request.OperateBy}");
                res.Code = ApiEnum.Error;
                res.Msg = $"结束工单失败：{ex.Message}";
            }

            return res;
        }
    }
}
